const express = require('express');
const router = express.Router();
const db = require('../config/database');

// 获取所有健康证
router.get('/', async (req, res) => {
  try {
    const [rows] = await db.promise().query('SELECT * FROM health_cards ORDER BY created_at DESC');
    res.json(rows);
  } catch (err) {
    console.error('获取健康证失败', err);
    res.status(500).json({ error: '获取健康证失败' });
  }
});

// 获取健康证索引（简化信息，只包含姓名和编号）
router.get('/index', async (req, res) => {
  try {
    const [rows] = await db.promise().query('SELECT unique_id, name, id_number as id FROM health_cards ORDER BY created_at DESC');
    
    // 将结果转换为前端期望的格式
    const indexData = {};
    rows.forEach(row => {
      indexData[row.unique_id] = {
        uniqueId: row.unique_id,
        name: row.name,
        id: row.id
      };
    });
    
    res.json(indexData);
  } catch (err) {
    console.error('获取健康证索引失败', err);
    res.status(500).json({ error: '获取健康证索引失败' });
  }
});

// 获取单个健康证
router.get('/:id', async (req, res) => {
  try {
    const [rows] = await db.promise().query('SELECT * FROM health_cards WHERE unique_id = ?', [req.params.id]);
    
    if (rows.length === 0) {
      return res.status(404).json({ error: '健康证不存在' });
    }

    // 转换数据格式以匹配前端期望的格式
    const healthCard = rows[0];
    const responseData = {
      name: healthCard.name,
      gender: healthCard.gender,
      id: healthCard.id_number,
      age: healthCard.age,
      type: healthCard.type,
      jobType: healthCard.job_title,
      issueDate: healthCard.issue_date,
      validDate: healthCard.expiry_date,
      result: healthCard.result,
      unit: healthCard.work_unit,
      hospital: healthCard.hospital,
      uniqueId: healthCard.unique_id,
      photoData: healthCard.photo_url,
      stampData: healthCard.stamp_url || 'img/zhang.png'
    };
    
    res.json(responseData);
  } catch (err) {
    console.error('获取健康证失败', err);
    res.status(500).json({ error: '获取健康证失败' });
  }
});

// 创建健康证
router.post('/', async (req, res) => {
  try {
    console.log('收到创建健康证请求, body字段:', Object.keys(req.body).join(', '));
    const {
      name, gender, id, age, type, jobType, issueDate, validDate, 
      result, unit, hospital, uniqueId, photoData, stampData
    } = req.body;

    console.log('解析的字段值:', {
      name, gender, id: id?.length > 10 ? id.substring(0, 10) + '...' : id, 
      age, type, jobType, issueDate, validDate, result, 
      unit: unit?.length > 10 ? unit.substring(0, 10) + '...' : unit, 
      hospital: hospital?.length > 10 ? hospital.substring(0, 10) + '...' : hospital, 
      uniqueId,
      hasPhotoData: !!photoData,
      hasStampData: !!stampData
    });

    // 验证必填字段
    if (!name || !gender || !id || !issueDate || !validDate || !unit || !uniqueId) {
      console.log('缺少必填字段:', {name, gender, id, issueDate, validDate, unit, uniqueId});
      return res.status(400).json({ error: '所有必填字段都需要提供' });
    }

    // 处理工作单位字段
    const workUnit = unit;

    // 处理数据库表字段映射
    let fields = ['name', 'gender', 'id_number', 'age', 'type', 'job_title', 
                 'issue_date', 'expiry_date', 'result', 'work_unit', 'hospital', 
                 'unique_id', 'photo_url', 'stamp_url'];
                 
    let placeholders = fields.map(() => '?').join(', ');
    let values = [
      name, gender, id, age || null, type || '食品卫生', jobType || '流通领域',
      issueDate, validDate, result || '合格', workUnit, hospital || '',
      uniqueId, photoData || null, stampData || '/img/zhang.png'
    ];

    const query = `
      INSERT INTO health_cards 
      (${fields.join(', ')})
      VALUES (${placeholders})
      ON DUPLICATE KEY UPDATE
        name = VALUES(name),
        gender = VALUES(gender), 
        id_number = VALUES(id_number),
        age = VALUES(age),
        type = VALUES(type),
        job_title = VALUES(job_title),
        issue_date = VALUES(issue_date),
        expiry_date = VALUES(expiry_date),
        result = VALUES(result),
        work_unit = VALUES(work_unit),
        hospital = VALUES(hospital),
        photo_url = VALUES(photo_url),
        stamp_url = VALUES(stamp_url)
    `;
    
    console.log('准备执行SQL INSERT/UPDATE');
    
    const [result1] = await db.promise().query(query, values);
    console.log('SQL执行结果:', result1);
    
    res.status(201).json({ 
      message: '健康证创建成功', 
      uniqueId: uniqueId 
    });
  } catch (err) {
    console.error('创建健康证失败', err);
    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({ error: '健康证编号已存在' });
    }
    res.status(500).json({ error: '创建健康证失败', message: err.message });
  }
});

// 更新健康证
router.put('/:id', async (req, res) => {
  try {
    const {
      name, gender, id, age, type, jobType, issueDate, validDate, 
      result, unit, hospital, photoData, stampData
    } = req.body;

    const uniqueId = req.params.id;

    // 验证必填字段
    if (!name || !gender || !id || !issueDate || !validDate || !unit) {
      return res.status(400).json({ error: '所有必填字段都需要提供' });
    }

    // 构建SQL查询
    const query = `
      UPDATE health_cards 
      SET name = ?, gender = ?, id_number = ?, age = ?, type = ?, 
          job_title = ?, issue_date = ?, expiry_date = ?, result = ?, 
          work_unit = ?, hospital = ?, photo_url = ?, stamp_url = ?
      WHERE unique_id = ?
    `;
    
    const values = [
      name, gender, id, age || null, type || '食品卫生', 
      jobType || '流通领域', issueDate, validDate, result || '合格', 
      unit, hospital || '', photoData || null, 
      stampData || '/img/zhang.png', uniqueId
    ];

    const [result1] = await db.promise().query(query, values);
    
    if (result1.affectedRows === 0) {
      return res.status(404).json({ error: '健康证不存在' });
    }
    
    res.json({ 
      message: '健康证更新成功',
      uniqueId: uniqueId
    });
  } catch (err) {
    console.error('更新健康证失败', err);
    res.status(500).json({ error: '更新健康证失败', message: err.message });
  }
});

// 删除健康证
router.delete('/:id', async (req, res) => {
  try {
    const uniqueId = req.params.id;
    
    const [result] = await db.promise().query('DELETE FROM health_cards WHERE unique_id = ?', [uniqueId]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: '健康证不存在' });
    }
    
    res.json({ message: '健康证删除成功' });
  } catch (err) {
    console.error('删除健康证失败', err);
    res.status(500).json({ error: '删除健康证失败' });
  }
});

// 批量删除健康证
router.post('/batch-delete', async (req, res) => {
  try {
    const { ids } = req.body;
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({ error: '需要提供要删除的ID数组' });
    }
    
    const placeholders = ids.map(() => '?').join(',');
    const [result] = await db.promise().query(
      `DELETE FROM health_cards WHERE unique_id IN (${placeholders})`, 
      ids
    );
    
    res.json({ 
      message: '批量删除成功',
      deletedCount: result.affectedRows
    });
  } catch (err) {
    console.error('批量删除健康证失败', err);
    res.status(500).json({ error: '批量删除健康证失败' });
  }
});

module.exports = router; 